package com.javaex.book.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

import com.javaex.book.utils.JdbcUtils;

/**
 * 使用Filter进行统一管理事务的提交和回滚
 *
 * @author 黄星琦
 * @Date 2022年3月2日
 */
@WebFilter("/*")
public class TransactionFilter implements Filter {

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		try {
			chain.doFilter(request, response);
			JdbcUtils.commitAndClose();
		} catch (Exception e) {
			JdbcUtils.rollbackAndClose();
		}
	}
}
